package nl.windgazer.arachne.pages;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import java.util.UUID;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;

import com.joostschouten.common.service.catpcha.CaptchaService;

public class CaptchaImage {
	
	public static final String CAPTCHA_ID_KEY = "com.joostschouten.common.http.tapestrybase.pages.CaptchaImage.CAPTCHA_ID_KEY";
	
	@Inject
	private CaptchaService _cs;
	
	@Inject
	private Locale locale;
	
	@Inject
	private Request request;
	
	@OnEvent(value = EventConstants.ACTIVATE)
	Object init() throws Exception {

		String captchaId =  UUID.randomUUID().toString();
		request.getSession(true).setAttribute(CAPTCHA_ID_KEY, captchaId);
		
		final ByteArrayInputStream output = new ByteArrayInputStream(_cs.getCaptcha(captchaId, locale));

        final StreamResponse response = new StreamResponse() {

            public String getContentType() {
                return "image/jpg";
            }

            public InputStream getStream() throws IOException {
                return output;
            }

            public void prepareResponse(Response response) {
            }
        };
        return response;
	}

}
